package com.springbootcrud.user.service.impl;

import com.springbootcrud.user.dao.MonitorDao;
import com.springbootcrud.user.entity.Index;
import com.springbootcrud.user.entity.LockTables;
import com.springbootcrud.user.entity.LogEntry;
import com.springbootcrud.user.entity.Space;
import com.springbootcrud.user.service.MonitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class MonitorServiceImpl implements MonitorService {
    @Autowired
    MonitorDao monitorDao;
    @Override
    public List<LogEntry> getAll( String bizdate) {
      List<LogEntry>  listLog= monitorDao.getAll(bizdate);
        return listLog;
    }

    @Override
    public void save(LogEntry logEntry) {

        monitorDao.sava(logEntry );


    }

    @Override
    public List<LogEntry> parseLog(String log,String path) {



        List<LogEntry> entries = new ArrayList<>();
        String[] logEntries = log.split("\n(?=\\d{2}:\\d{2}:\\d{2}\\.\\d{3})"); // 按时间戳分割日志条目
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String yesterday = sdf.format(cal.getTime());

        for (String entryText : logEntries) {
            LogEntry entry = new LogEntry();

            // 匹配日志头信息
            Matcher matcher = LOG_PATTERN.matcher(entryText);
            System.out.println("matcher"+matcher);
            if (matcher.find()) {
                entry.setFtimestamp(yesterday+" "+matcher.group(1));
                entry.setFthread(matcher.group(2));
                entry.setFlevel(matcher.group(3));
                entry.setFlogger(path);
                entry.setFmessage(matcher.group(5));

            }
            entries.add(entry);
        }

        return entries;
    }

    @Override
    public List<Space> getSpaceAll() {
        List<Space>  listLog= monitorDao.getSpaceAll();
        return listLog;
    }

    @Override
    public List<Index> getIndexAll() {
        List<Index>  listLog= monitorDao.getIndexAll();
        return listLog;
    }

    @Override
    public List<LockTables> getLockAll() {
        List<LockTables>  listLog= monitorDao.getLockAll();
        return listLog;
    }

    private static final Pattern LOG_PATTERN = Pattern.compile(
            //  "(\\d{2}:\\d{2}:\\d{2}\\.\\d{3})\\s+\\[(.*?)\\]\\s+(\\w+)\\s+(\\w+)\\s+(.*?)(\\n(.*))?"
            "(\\d{2}:\\d{2}:\\d{2}\\.\\d{3})\\s+\\[(.*?)\\]\\s+(\\w+)\\s+(.*?)\\s+(\\n(.*))?\\s"
    );
}
